package org.wangp.framework.core.domain;

import org.springframework.http.HttpStatus;
import org.wangp.framework.core.exception.BusinessException;

/**
 * @author wangpeng (๑•ᴗ•๑)
 * @since 2021/10/24 17:53
 */
public class CommonResult<T> {
	private boolean success = false;
	private int code = -1;
	private String message = "";
	private long total = 0;
	private T data;

	public boolean isSuccess() {
		return this.success;
	}

	public CommonResult<T> setSuccess(final boolean success) {
		this.success = success;
		return this;
	}

	public int getCode() {
		return this.code;
	}

	public CommonResult<T> setCode(final int code) {
		this.code = code;
		return this;
	}

	public String getMessage() {
		return this.message;
	}

	public CommonResult<T> setMessage(final String message) {
		this.message = message;
		return this;
	}

	public long getTotal() {
		return this.total;
	}

	public CommonResult<T> setTotal(final long total) {
		this.total = total;
		return this;
	}

	public T getData() {
		return this.data;
	}

	public CommonResult<T> setData(final T data) {
		this.data = data;
		return this;
	}

	public static <E> CommonResult<E> success(final E data) {
		return success(data, HttpStatus.OK.getReasonPhrase());
	}

	public static <E> CommonResult<E> success(final E data, final long total) {
		return success(data, HttpStatus.OK.getReasonPhrase()).setTotal(total);
	}

	public static <E> CommonResult<E> success(final E data, final String message) {
		return success(data, message, HttpStatus.OK.value());
	}

	public static <E> CommonResult<E> success(final E data, final String message, final int code) {
		return new CommonResult<E>().setCode(code).setData(data).setMessage(message).setSuccess(true);
	}

	public static <E> CommonResult<E> success() {
		return new CommonResult<E>().setCode(HttpStatus.OK.value()).setMessage(HttpStatus.OK.getReasonPhrase())
				.setSuccess(true);
	}

	public static <E> CommonResult<E> fail() {
		return fail(HttpStatus.BAD_GATEWAY.getReasonPhrase());
	}

	public static <E> CommonResult<E> fail(final String message) {
		return fail(message, HttpStatus.BAD_REQUEST.value());
	}

	public static <E> CommonResult<E> fail(final String message, final int code) {
		return new CommonResult<E>().setCode(code).setMessage(message).setSuccess(false);
	}

	public static <E> CommonResult<E> exceptionFail(final BusinessException exception) {
		return new CommonResult<E>().setCode(exception.getCode()).setMessage(exception.getMessage())
				.setSuccess(false);
	}
}
